﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Media;
using System.Text;
using System.Threading;

/// <summary>
/// File
/// </summary>
namespace HK2009.Common
{
    public class FileTools
    {
        public FileTools()
        {
            //
            // TODO: 
            //
        }


        /// <summary> 
        /// Write file 
        /// WriteFile("generate\2008.html","I am a good man")
        /// </summary> 
        /// <param name="sFileName">filepath(dummy path)</param> 
        /// <param name="fileContent">file contant</param> 
        /// <returns></returns> 
        public static void WriteFile(string sFileName, string fileContent)
        {
            if (sFileName.IndexOf("/") >= 0)
            {
                sFileName = HttpContext.Current.Server.MapPath(sFileName);
            }
            if (File.Exists(sFileName))
            {
                File.Delete(sFileName);
            }
            using (StreamWriter sw = File.CreateText(sFileName))
            {
                sw.WriteLine(fileContent);
                sw.Close();
            }
        }

        /// <summary>
        /// 
        /// ReadFile(\\template\\index.html)
        /// </summary>
        /// <param name="sFileName"></param>
        /// <returns></returns>
        public static string ReadFile(string sFileName)
        {
            string FileName = HttpContext.Current.Server.MapPath(sFileName);
            string template = File.ReadAllText(FileName, System.Text.Encoding.UTF8);
            return template;
        }
        /// <summary> 
        /// 删除文件 
        /// DeleteFile("test.jpg")
        /// </summary> 
        /// <param name="sFileName">要删除的文件名(带路径，支持虚拟路径)</param> 
        public static void DeleteFile(string sFileName)
        {
            if (sFileName.IndexOf("/") != -1)
            {
                sFileName = HttpContext.Current.Server.MapPath(sFileName);
            }
            try
            {
                if (File.Exists(sFileName))
                {
                    File.Delete(sFileName);
                }
            }
            catch
            {
                throw;
            }

        }


        /// <summary>
        /// 文件是否存在
        /// </summary>
        /// <param name="sFileName"></param>
        /// <returns></returns>
        public static bool IsExists(string sFileName)
        {
            try
            {
                //if (sFileName.IndexOf("\\") != -1)
                //{
                sFileName = HttpContext.Current.Server.MapPath(sFileName);
                //}
                if (File.Exists(sFileName))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                throw;
            }
        }


        /// <summary> 
        /// 自动生成文件名(不带扩展名)         
        /// </summary> 
        /// <returns></returns> 
        public static string AutoFileName()
        {
            return DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') +
                DateTime.Now.Day.ToString().PadLeft(2, '0') + DateTime.Now.Hour.ToString().PadLeft(2, '0') +
                DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0') +
                DateTime.Now.Millisecond.ToString().PadLeft(3, '0');
        }


        /// <summary> 
        /// 自动生成文件名(不带扩展名)         
        /// </summary> 
        /// <returns></returns> 
        public static string AutoFileName(string str)
        {
            return str + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') +
                DateTime.Now.Day.ToString().PadLeft(2, '0') + DateTime.Now.Hour.ToString().PadLeft(2, '0') +
                DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0') +
                DateTime.Now.Millisecond.ToString().PadLeft(3, '0') ;
        }


        /// <summary> 
        /// 按yyyy/mm/dd格式创建目录 
        /// MakeDirByDay("\\upload")
        /// </summary> 
        /// <param name="virturlPath">主虚拟路径</param> 
        /// <returns>创建后的虚拟路径</returns> 
        public static string MakeDirByDay(string virturlPath)
        {
            string sYear = DateTime.Now.Year.ToString();
            string sMonth = DateTime.Now.Month.ToString();
            string sDay = DateTime.Now.Day.ToString();
            string folderName = "";

            folderName = HttpContext.Current.Server.MapPath(virturlPath);
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            folderName = HttpContext.Current.Server.MapPath(virturlPath + "/" + sYear);
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            folderName = HttpContext.Current.Server.MapPath(virturlPath + "/" + sYear + "/" + sMonth.PadLeft(2, '0'));
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            folderName = HttpContext.Current.Server.MapPath(virturlPath + "/" + sYear + "/" + sMonth.PadLeft(2, '0') + "/" + sDay.PadLeft(2, '0'));
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            string returnstr;
            returnstr = virturlPath + "/" + sYear + "/" + sMonth.PadLeft(2, '0') + "/" + sDay.PadLeft(2, '0') + "/";
            returnstr = returnstr.Replace("//", "/");
            return returnstr;
        }


        /// <summary> 
        /// 按yyyy/mm格式创建目录 
        /// MakeDirByMonth("\\upload")
        /// </summary> 
        /// <param name="virturlPath">主虚拟路径</param> 
        /// <returns>创建后的虚拟路径</returns> 
        public static string MakeDirByMonth(string virturlPath)
        {
            string sYear = DateTime.Now.Year.ToString();
            string sMonth = DateTime.Now.Month.ToString();
            string folderName = "";

            folderName = HttpContext.Current.Server.MapPath(virturlPath);
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            folderName = HttpContext.Current.Server.MapPath(virturlPath + "/" + sYear);
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            folderName = HttpContext.Current.Server.MapPath(virturlPath + "/" + sYear + "/" + sMonth.PadLeft(2, '0'));
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            string returnstr;
            returnstr = virturlPath + "/" + sYear + "/" + sMonth.PadLeft(2, '0') + "/";
            returnstr = returnstr.Replace("//", "/");
            return returnstr;
        }


        /// <summary> 
        /// 按yyyy格式创建目录 
        /// MakeDirByYear("\\upload")
        /// </summary> 
        /// <param name="virturlPath">主虚拟路径</param> 
        /// <returns>创建后的虚拟路径</returns> 
        public static string MakeDirByYear(string virturlPath)
        {
            string sYear = DateTime.Now.Year.ToString();
            string sMonth = DateTime.Now.Month.ToString();
            string folderName = "";

            folderName = HttpContext.Current.Server.MapPath(virturlPath);
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            folderName = HttpContext.Current.Server.MapPath(virturlPath + "/" + sYear);
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            string returnstr;
            returnstr = virturlPath + "/" + sYear + "/";
            returnstr = returnstr.Replace("//", "/");
            return returnstr;
        }

        /// <summary> 
        /// 直接创建目录 
        /// MakeDir("\\upload")
        /// </summary> 
        /// <param name="virturlPath">主虚拟路径</param> 
        /// <returns>创建后的虚拟路径</returns> 
        public static string MakeDir(string virturlPath)
        {
            string folderName = "";

            folderName = HttpContext.Current.Server.MapPath(virturlPath);
            folderName.Replace("//", "/");
            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }

            string returnstr;
            returnstr = virturlPath + "/" ;
            returnstr = returnstr.Replace("//", "/");
            return returnstr;
        }

        /// <summary>
        /// 弹出JavaScript小窗口
        /// </summary>
        /// <param name="js">窗口信息</param>
        public static void Alert(string message)
        {
            #region


            string js = @"<Script language='JavaScript'>
                    alert('" + message + "');</Script>";
            HttpContext.Current.Response.Write(js);
            #endregion
        }

        /// <summary>
        /// 弹出消息框并且转向到新的URL
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="toURL">连接地址</param>
        public static void AlertAndRedirect(string message, string toURL)
        {
            #region
            string js = "<script language=javascript>alert('{0}');window.location.replace('{1}')</script>";
            HttpContext.Current.Response.Write(string.Format(js, message, toURL));
            HttpContext.Current.Response.End();
            #endregion
        }

         ///   <summary>   
        ///   输出硬盘文件，提供下载   
        ///   </summary>   
         ///   <param   name="_Request">Page.Request对象</param>   
         ///   <param   name="_Response">Page.Response对象</param>   
         ///   <param   name="_fileName">下载文件名</param>   
        ///   <param   name="_fullPath">带文件名下载路径</param>   
         ///   <param   name="_speed"><每秒允许下载的字节数/param>   
         ///   <returns>返回是否成功</returns>   
        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                //建立文件对象   
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                //建立流读对象   
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    int pack = 10240;   //10K   bytes   
                    //int   sleep   =   200;       //每秒5次       即5*10K   bytes每秒   
                    int sleep = (int)Math.Floor(double.Parse(Convert.ToString(1000 * pack / _speed))) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format("   bytes   {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName+Path.GetExtension(_fullPath), System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor(double.Parse(Convert.ToString((fileLength - startBytes) / pack))) + 1;
                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;

                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

        public static void Export(string fileName)
        {
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName );
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.ContentType = "application/vnd.ms-txt";
            HttpContext.Current.Response.Charset = "";

            HttpContext.Current.Response.WriteFile(fileName);
            
            HttpContext.Current.Response.End();
        }
     

    }
}

